package com.example.hsh.homefragment.http;

import android.content.Context;


import com.example.hsh.homefragment.BuildConfig;
import com.example.hsh.homefragment.utils.NetworkUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 * Created by only on 16/10/19.
 * Email: onlybeyond99@gmail.com
 * 保证全局只有一个设置相同的OkHttpClient
 */

public class OKHttpUtil {
    private static final String TAG = "OKHttpUtil";

    private static final int maxTryNum = 3;

    private static OkHttpClient mOkHttpClient;

    public static void setOkHttpClient(OkHttpClient okHttpClient) {
        mOkHttpClient = okHttpClient;
    }

    public static void init(Context context) {
        if (mOkHttpClient == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            RetryIntercepter retryIntercepter = new RetryIntercepter(maxTryNum);
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            mOkHttpClient = new OkHttpClient.Builder()
                    .readTimeout(10000L, TimeUnit.MILLISECONDS)
                    .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                    .addInterceptor(interceptor)
                    .addInterceptor(retryIntercepter)
                    .addInterceptor(getReuseCacheInterceptor(context))
                    .addNetworkInterceptor(getNetWorkInterceptor(context))
                    .build();
        }
    }

    public static OkHttpClient getOkHttpClient(Context context) {
        if (mOkHttpClient == null) {
            //最基本的设置
            init(context);
        }
        return mOkHttpClient;
    }

    /**
     * 设置缓存，对于需要重用缓存减少请求的页面可以使用，缓存时间为60秒
     * @param context
     * @return
     */
    public static Interceptor getNetWorkInterceptor(final Context context) {
        return chain -> {
            Request request = chain.request();
            Response response = chain.proceed(request);
            /*if (NetworkUtils.isAvailable(context)) {*/

            //请求成功才进行缓存有效期设置，进行重用
            if (response.isSuccessful()) {

                //读取接口上通过@Header设置的缓存有效期
                String cacheControl = request.cacheControl().toString();

                response.newBuilder()
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            }
            /*} else {
                //无网络是并不会走该拦截器，所以这里的条件并没有用
                // 无网络时，设置超时为1周
                int maxStale = 60 * 60 * 24 * 7;
                response.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build();
            }*/
            return response;
        };
    }

    /**
     * 无网络时重用缓存
     * @param context
     * @return
     */
    public static Interceptor getReuseCacheInterceptor(final Context context) {
        return chain -> {
            Request request = chain.request();
            if (!NetworkUtils.isAvailable(context)) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            return chain.proceed(request);
        };
    }


}
